"""
主GUI界面
优化的分类展示Meiya SQL生成工具界面
"""

import customtkinter as ctk
import tkinter.filedialog as filedialog
import tkinter.messagebox as messagebox
import json
import os
import threading
from typing import Optional, Dict, List, Any
from collections import defaultdict

from constants import GUIConfig, Messages
from excel_parser import ExcelParser


class ConfigManager:
    """配置管理器，用于保存和读取用户配置"""
    
    @staticmethod
    def load_config() -> dict:
        """加载配置文件"""
        try:
            if os.path.exists(GUIConfig.CONFIG_FILE):
                with open(GUIConfig.CONFIG_FILE, 'r', encoding='utf-8') as f:
                    return json.load(f)
        except Exception as e:
            print(f"加载配置文件失败: {e}")
        
        return {"last_directory": os.path.expanduser("~")}
    
    @staticmethod
    def save_config(config: dict) -> None:
        """保存配置文件"""
        try:
            with open(GUIConfig.CONFIG_FILE, 'w', encoding='utf-8') as f:
                json.dump(config, f, ensure_ascii=False, indent=2)
        except Exception as e:
            print(f"保存配置文件失败: {e}")


class MeiyaSQLGenerator:
    """Meiya SQL生成工具主界面类"""
    
    def __init__(self):
        # 设置高DPI支持
        ctk.set_widget_scaling(1.0)
        ctk.set_window_scaling(1.0)
        
        # 初始化customtkinter
        ctk.set_appearance_mode("dark")
        ctk.set_default_color_theme("blue")
        
        # 创建主窗口
        self.root = ctk.CTk()
        self.root.title("🚀 Meiya SQL生成工具")
        self.root.geometry("1200x800")
        self.root.minsize(1100, 750)
        
        # 居中显示窗口
        self._center_window()
        
        # 初始化变量
        self.config = ConfigManager.load_config()
        self.selected_file_path = ""
        self.excel_parser = ExcelParser()
        self.current_step = 1
        self.parsed_data = []
        self.grouped_data = {}
        self.current_database = ""
        self.current_requirement = ""
        
        # 创建界面
        self._create_widgets()
        
        # 绑定窗口关闭事件
        self.root.protocol("WM_DELETE_WINDOW", self._on_closing)
    
    def _center_window(self):
        """将窗口居中显示"""
        self.root.update_idletasks()
        width = self.root.winfo_width()
        height = self.root.winfo_height()
        x = (self.root.winfo_screenwidth() // 2) - (width // 2)
        y = (self.root.winfo_screenheight() // 2) - (height // 2)
        self.root.geometry(f"{width}x{height}+{x}+{y}")
    
    def _create_widgets(self):
        """创建所有界面组件"""
        # 创建主容器
        self.main_frame = ctk.CTkFrame(self.root, fg_color="transparent")
        self.main_frame.pack(fill="both", expand=True, padx=20, pady=20)
        
        # 创建顶部标题区域
        self._create_compact_header()
        
        # 创建主要内容区域
        self._create_main_content()
    
    def _create_compact_header(self):
        """创建紧凑的标题区域"""
        header_frame = ctk.CTkFrame(
            self.main_frame,
            height=80,
            corner_radius=12,
            fg_color=("#2b5ce6", "#1f4cbf")
        )
        header_frame.pack(fill="x", pady=(0, 15))
        header_frame.pack_propagate(False)
        
        # 左侧标题信息
        title_container = ctk.CTkFrame(header_frame, fg_color="transparent")
        title_container.pack(side="left", fill="y", padx=25, pady=15)
        
        title_label = ctk.CTkLabel(
            title_container,
            text="🚀 Meiya SQL生成工具",
            font=ctk.CTkFont(family="Microsoft YaHei", size=24, weight="bold"),
            text_color="#ffffff"
        )
        title_label.pack(anchor="w")
        
        subtitle_label = ctk.CTkLabel(
            title_container,
            text="需求号 → Excel解析 → 分类展示 → SQL生成",
            font=ctk.CTkFont(family="Microsoft YaHei", size=13),
            text_color="#e6f1ff"
        )
        subtitle_label.pack(anchor="w", pady=(2, 0))
        
        # 右侧步骤指示器
        self._create_step_indicator(header_frame)
    
    def _create_step_indicator(self, parent):
        """创建步骤指示器"""
        step_frame = ctk.CTkFrame(parent, fg_color="transparent")
        step_frame.pack(side="right", padx=25, pady=15)
        
        steps = ["选择文件", "解析数据", "分类展示"]
        self.step_labels = []
        
        for i, step in enumerate(steps, 1):
            step_container = ctk.CTkFrame(step_frame, fg_color="transparent")
            step_container.pack(side="left", padx=8)
            
            # 步骤圆圈
            circle_color = "#28a745" if i <= self.current_step else "#6c757d"
            step_circle = ctk.CTkLabel(
                step_container,
                text=str(i),
                font=ctk.CTkFont(family="Microsoft YaHei", size=14, weight="bold"),
                text_color="#ffffff",
                fg_color=circle_color,
                corner_radius=15,
                width=30,
                height=30
            )
            step_circle.pack()
            
            # 步骤文字
            step_label = ctk.CTkLabel(
                step_container,
                text=step,
                font=ctk.CTkFont(family="Microsoft YaHei", size=11),
                text_color="#ffffff" if i <= self.current_step else "#cccccc"
            )
            step_label.pack(pady=(2, 0))
            
            self.step_labels.append((step_circle, step_label))
    
    def _create_main_content(self):
        """创建主要内容区域"""
        # 创建左右分栏布局
        content_frame = ctk.CTkFrame(self.main_frame, fg_color="transparent")
        content_frame.pack(fill="both", expand=True)
        
        # 左侧操作区域（固定）
        left_frame = ctk.CTkFrame(content_frame, width=450, corner_radius=12)
        left_frame.pack(side="left", fill="y", padx=(0, 10))
        left_frame.pack_propagate(False)
        
        # 右侧结果区域（切换式）
        right_frame = ctk.CTkFrame(content_frame, corner_radius=12)
        right_frame.pack(side="right", fill="both", expand=True)
        
        # 创建左侧操作面板
        self._create_operation_panel(left_frame)
        
        # 创建右侧结果面板
        self._create_result_panel(right_frame)
    
    def _create_operation_panel(self, parent):
        """创建左侧操作面板"""
        # 文件选择区域
        file_section = ctk.CTkFrame(parent, fg_color="transparent")
        file_section.pack(fill="x", padx=20, pady=(20, 15))
        
        step1_label = ctk.CTkLabel(
            file_section,
            text="📁 步骤1: 选择Excel文件",
            font=ctk.CTkFont(family="Microsoft YaHei", size=16, weight="bold")
        )
        step1_label.pack(anchor="w", pady=(0, 10))
        
        # 文件路径显示
        self.file_path_var = ctk.StringVar(value="请选择Excel文件...")
        self.file_path_entry = ctk.CTkEntry(
            file_section,
            textvariable=self.file_path_var,
            state="readonly",
            font=ctk.CTkFont(family="Microsoft YaHei", size=12),
            height=40
        )
        self.file_path_entry.pack(fill="x", pady=(0, 10))
        
        # 浏览按钮
        self.browse_button = ctk.CTkButton(
            file_section,
            text="🔍 浏览选择文件",
            command=self._browse_file,
            font=ctk.CTkFont(family="Microsoft YaHei", size=14, weight="bold"),
            height=45,
            corner_radius=8
        )
        self.browse_button.pack(fill="x")
        
        # 分隔线
        separator1 = ctk.CTkFrame(parent, height=1, fg_color=("#e0e0e0", "#404040"))
        separator1.pack(fill="x", padx=20, pady=15)
        
        # 解析操作区域
        parse_section = ctk.CTkFrame(parent, fg_color="transparent")
        parse_section.pack(fill="x", padx=20, pady=15)
        
        step2_label = ctk.CTkLabel(
            parse_section,
            text="⚡ 步骤2: 解析处理",
            font=ctk.CTkFont(family="Microsoft YaHei", size=16, weight="bold")
        )
        step2_label.pack(anchor="w", pady=(0, 10))
        
        # 解析按钮
        self.parse_button = ctk.CTkButton(
            parse_section,
            text="🚀 开始解析Excel",
            command=self._parse_excel,
            font=ctk.CTkFont(family="Microsoft YaHei", size=16, weight="bold"),
            height=50,
            corner_radius=8,
            fg_color=("#28a745", "#20c997"),
            hover_color=("#218838", "#17a2b8"),
            state="disabled"
        )
        self.parse_button.pack(fill="x", pady=(0, 10))
        
        # 进度条
        self.progress_bar = ctk.CTkProgressBar(parse_section, height=15, corner_radius=8)
        self.progress_bar.pack(fill="x", pady=(0, 5))
        self.progress_bar.set(0)
        
        # 进度文字
        self.progress_label = ctk.CTkLabel(
            parse_section,
            text="🟢 就绪",
            font=ctk.CTkFont(family="Microsoft YaHei", size=12, weight="bold"),
            text_color=("#28a745", "#20c997")
        )
        self.progress_label.pack(anchor="w")
        
        # 分隔线
        separator2 = ctk.CTkFrame(parent, height=1, fg_color=("#e0e0e0", "#404040"))
        separator2.pack(fill="x", padx=20, pady=15)
        
        # 统计区域
        stats_section = ctk.CTkFrame(parent, fg_color="transparent")
        stats_section.pack(fill="x", padx=20, pady=15)
        
        stats_label = ctk.CTkLabel(
            stats_section,
            text="📊 按数据库统计",
            font=ctk.CTkFont(family="Microsoft YaHei", size=16, weight="bold")
        )
        stats_label.pack(anchor="w", pady=(0, 10))
        
        # 统计信息容器
        self.stats_container = ctk.CTkFrame(stats_section, corner_radius=8)
        self.stats_container.pack(fill="x")
        
        self.stats_text = ctk.CTkLabel(
            self.stats_container,
            text="等待解析数据...",
            font=ctk.CTkFont(family="Microsoft YaHei", size=12),
            justify="left"
        )
        self.stats_text.pack(padx=15, pady=15)
        
        # 底部操作按钮
        bottom_section = ctk.CTkFrame(parent, fg_color="transparent")
        bottom_section.pack(fill="x", side="bottom", padx=20, pady=20)
        
        button_container = ctk.CTkFrame(bottom_section, fg_color="transparent")
        button_container.pack(fill="x")
        
        # 重置按钮
        self.clear_button = ctk.CTkButton(
            button_container,
            text="🔄 重置",
            command=self._clear_all,
            font=ctk.CTkFont(family="Microsoft YaHei", size=14),
            height=40,
            width=100,
            corner_radius=8,
            fg_color=("#6c757d", "#5a6268")
        )
        self.clear_button.pack(side="left")
        
        # 帮助按钮
        help_button = ctk.CTkButton(
            button_container,
            text="❓ 帮助",
            command=self._show_help,
            font=ctk.CTkFont(family="Microsoft YaHei", size=14),
            height=40,
            width=100,
            corner_radius=8,
            fg_color=("#17a2b8", "#138496")
        )
        help_button.pack(side="right")
    
    def _create_result_panel(self, parent):
        """创建右侧结果面板"""
        # 标题区域
        title_frame = ctk.CTkFrame(parent, height=50, corner_radius=8)
        title_frame.pack(fill="x", padx=15, pady=(15, 10))
        title_frame.pack_propagate(False)
        
        title_label = ctk.CTkLabel(
            title_frame,
            text="📋 步骤3: 解析结果",
            font=ctk.CTkFont(family="Microsoft YaHei", size=16, weight="bold")
        )
        title_label.pack(side="left", padx=15, pady=15)
        
        # 初始显示区域
        self.initial_display = ctk.CTkFrame(parent, corner_radius=8)
        self.initial_display.pack(fill="both", expand=True, padx=15, pady=(0, 15))
        
        welcome_text = """🎉 欢迎使用 Meiya SQL生成工具！

📋 使用步骤:
1️⃣ 点击左侧"浏览选择文件"选择Excel文件
2️⃣ 点击"开始解析Excel"处理数据  
3️⃣ 解析完成后，右侧会显示按数据库分类的结果

📄 新版Excel文件格式要求:
• 必须包含6列: 需求号、数据库、脚本类别、SQL脚本、备注、RollBack脚本
• 需求号: 需求编号（必填，新增字段）
• 数据库类型: iclaim, cclaim, adapter
• 脚本类别: DDL, DML

✨ 解析后的功能:
• 自动按数据库分类展示（iclaim、cclaim、adapter）
• 按需求号分组显示DDL/DML统计
• 点击需求号查看格式化SQL脚本
• 支持切换查看RollBack脚本

💡 提示: 相同需求号的记录会自动分组显示"""

        self.welcome_text = ctk.CTkTextbox(
            self.initial_display,
            font=ctk.CTkFont(family="Microsoft YaHei", size=13),
            wrap="word"
        )
        self.welcome_text.pack(fill="both", expand=True, padx=20, pady=20)
        self.welcome_text.insert("0.0", welcome_text)
        self.welcome_text.configure(state="disabled")
        
        # 数据库选项卡（初始隐藏）
        self.db_tabview = None
    
    def _browse_file(self):
        """浏览选择Excel文件"""
        initial_dir = self.config.get("last_directory", os.path.expanduser("~"))
        
        file_path = filedialog.askopenfilename(
            title="选择Excel文件 - Meiya SQL生成工具",
            initialdir=initial_dir,
            filetypes=GUIConfig.SUPPORTED_FORMATS
        )
        
        if file_path:
            self.selected_file_path = file_path
            filename = os.path.basename(file_path)
            self.file_path_var.set(f"✅ {filename}")
            
            # 更新配置
            self.config["last_directory"] = os.path.dirname(file_path)
            ConfigManager.save_config(self.config)
            
            # 启用解析按钮
            self.parse_button.configure(state="normal")
            self._update_step_indicator(2)
            self.progress_label.configure(text="🟡 文件已选择，可以开始解析")
    
    def _parse_excel(self):
        """解析Excel文件"""
        if not self.selected_file_path:
            messagebox.showwarning("⚠️ 警告", "请先选择Excel文件！")
            return
        
        threading.Thread(target=self._parse_excel_thread, daemon=True).start()
    
    def _parse_excel_thread(self):
        """后台解析线程"""
        try:
            self.root.after(0, lambda: self._set_parsing_state(True))
            
            success, message, data = self.excel_parser.parse_excel(self.selected_file_path)
            
            if success:
                self.root.after(0, lambda: self._on_parse_success(data))
                print("\n" + "="*80)
                print("🚀 Meiya SQL生成工具 - 详细解析报告")
                print("="*80)
                self.excel_parser.print_data_summary()
                print("="*80)
            else:
                self.root.after(0, lambda: self._on_parse_error(message))
        
        except Exception as e:
            error_msg = f"解析过程中发生错误: {str(e)}"
            self.root.after(0, lambda: self._on_parse_error(error_msg))
    
    def _set_parsing_state(self, parsing: bool):
        """设置解析状态"""
        if parsing:
            self.parse_button.configure(state="disabled", text="⏳ 解析中...")
            self.browse_button.configure(state="disabled")
            self.clear_button.configure(state="disabled")
            self.progress_bar.set(0.6)
            self.progress_label.configure(text="🔄 正在解析Excel文件...", text_color=("#ffc107", "#ffcd39"))
        else:
            self.parse_button.configure(state="normal", text="🚀 开始解析Excel")
            self.browse_button.configure(state="normal")
            self.clear_button.configure(state="normal")
            self.progress_bar.set(0)
    
    def _on_parse_success(self, data):
        """解析成功处理"""
        self._set_parsing_state(False)
        self.progress_bar.set(1.0)
        self.progress_label.configure(text="✅ 解析完成", text_color=("#28a745", "#20c997"))
        self._update_step_indicator(3)
        
        # 保存解析数据
        self.parsed_data = data
        self._group_data_by_database()
        
        # 更新统计信息
        self._update_database_stats()
        
        # 创建数据库选项卡
        self._create_database_tabs()
        
        messagebox.showinfo("🎉 解析成功", f"Excel解析完成！\n共处理 {len(data)} 条记录\n已按数据库分类展示")
    
    def _group_data_by_database(self):
        """按数据库分组数据"""
        self.grouped_data = defaultdict(lambda: defaultdict(list))
        
        for item in self.parsed_data:
            database = item['database']
            requirement_no = item['requirement_no']
            self.grouped_data[database][requirement_no].append(item)
    
    def _update_database_stats(self):
        """更新数据库统计信息"""
        if not self.grouped_data:
            return
        
        stats_text = "📊 数据库分布统计:\n\n"
        for database in sorted(self.grouped_data.keys()):
            req_count = len(self.grouped_data[database])
            total_records = sum(len(records) for records in self.grouped_data[database].values())
            stats_text += f"🗄️ {database.upper()}\n"
            stats_text += f"   需求数: {req_count}\n"
            stats_text += f"   记录数: {total_records}\n\n"
        
        self.stats_text.configure(text=stats_text)
    
    def _create_database_tabs(self):
        """创建数据库选项卡"""
        # 隐藏初始显示
        self.initial_display.pack_forget()
        
        # 创建数据库选项卡
        self.db_tabview = ctk.CTkTabview(self.initial_display.master, corner_radius=8)
        self.db_tabview.pack(fill="both", expand=True, padx=15, pady=(0, 15))
        
        # 为每个数据库创建选项卡
        for database in sorted(self.grouped_data.keys()):
            db_display = f"🗄️ {database.upper()}"
            tab = self.db_tabview.add(db_display)
            self._create_database_view(tab, database)
    
    def _create_database_view(self, parent, database):
        """创建数据库视图"""
        # 创建左右分栏
        main_container = ctk.CTkFrame(parent, fg_color="transparent")
        main_container.pack(fill="both", expand=True, padx=10, pady=10)
        
        # 左侧需求列表
        left_frame = ctk.CTkFrame(main_container, width=300, corner_radius=8)
        left_frame.pack(side="left", fill="y", padx=(0, 5))
        left_frame.pack_propagate(False)
        
        # 右侧SQL显示
        right_frame = ctk.CTkFrame(main_container, corner_radius=8)
        right_frame.pack(side="right", fill="both", expand=True)
        
        self._create_requirement_list(left_frame, database)
        self._create_sql_display(right_frame, database)
    
    def _create_requirement_list(self, parent, database):
        """创建需求列表"""
        # 标题
        title_label = ctk.CTkLabel(
            parent,
            text=f"📋 {database.upper()} 需求列表",
            font=ctk.CTkFont(family="Microsoft YaHei", size=14, weight="bold")
        )
        title_label.pack(anchor="w", padx=15, pady=(15, 10))
        
        # 滚动框架
        scroll_frame = ctk.CTkScrollableFrame(parent, corner_radius=8)
        scroll_frame.pack(fill="both", expand=True, padx=15, pady=(0, 15))
        
        # 生成需求按钮
        requirements = sorted(self.grouped_data[database].keys())
        for req_no in requirements:
            items = self.grouped_data[database][req_no]
            
            # 统计DDL和DML数量
            ddl_count = sum(1 for item in items if item['script_type'] == 'DDL')
            dml_count = sum(1 for item in items if item['script_type'] == 'DML')
            
            # 创建需求按钮
            req_text = f"{req_no}\n📝 DDL: {ddl_count}  DML: {dml_count}"
            
            req_button = ctk.CTkButton(
                scroll_frame,
                text=req_text,
                command=lambda db=database, req=req_no: self._select_requirement(db, req),
                font=ctk.CTkFont(family="Microsoft YaHei", size=12),
                height=60,
                corner_radius=8,
                anchor="w"
            )
            req_button.pack(fill="x", pady=2)
    
    def _create_sql_display(self, parent, database):
        """创建SQL显示区域"""
        # 顶部工具栏
        toolbar = ctk.CTkFrame(parent, height=50, corner_radius=8)
        toolbar.pack(fill="x", padx=15, pady=(15, 5))
        toolbar.pack_propagate(False)
        
        # 当前选择显示
        selection_label = ctk.CTkLabel(
            toolbar,
            text="请选择左侧需求查看SQL脚本",
            font=ctk.CTkFont(family="Microsoft YaHei", size=14, weight="bold")
        )
        selection_label.pack(side="left", padx=15, pady=15)
        
        # RollBack切换按钮
        rollback_var = ctk.BooleanVar()
        rollback_switch = ctk.CTkSwitch(
            toolbar,
            text="显示RollBack脚本",
            variable=rollback_var,
            font=ctk.CTkFont(family="Microsoft YaHei", size=12)
        )
        rollback_switch.pack(side="right", padx=15, pady=15)
        
        # 保存引用以便后续更新
        setattr(parent, 'selection_label', selection_label)
        setattr(parent, 'rollback_var', rollback_var)
        setattr(parent, 'rollback_switch', rollback_switch)
        
        # SQL文本显示区域
        sql_textbox = ctk.CTkTextbox(
            parent,
            font=ctk.CTkFont(family="Consolas", size=13),
            wrap="none"
        )
        sql_textbox.pack(fill="both", expand=True, padx=15, pady=(0, 15))
        
        # 保存引用
        setattr(parent, 'sql_textbox', sql_textbox)
        
        # 初始化显示
        initial_text = f"""-- {database.upper()} 数据库SQL脚本
-- 请从左侧选择需求号查看详细SQL脚本

💡 使用说明:
• 点击左侧需求号按钮查看对应的SQL脚本
• 使用右上角开关切换查看RollBack脚本
• SQL脚本按以下格式显示:
  -- 数据库名
  -- 需求号 备注信息
  SQL语句内容

🔄 RollBack脚本功能:
• 开启开关后显示回滚脚本
• 没有回滚脚本的记录会显示提示信息"""

        sql_textbox.insert("0.0", initial_text)
        sql_textbox.configure(state="disabled")
        
        # 绑定切换事件
        rollback_switch.configure(command=lambda: self._refresh_sql_display(parent, database))
    
    def _select_requirement(self, database, requirement_no):
        """选择需求"""
        self.current_database = database
        self.current_requirement = requirement_no
        
        # 找到对应的SQL显示区域
        db_display = f"🗄️ {database.upper()}"
        if self.db_tabview and db_display in self.db_tabview._tab_dict:
            tab_frame = self.db_tabview._tab_dict[db_display]
            # 找到SQL显示区域
            for child in tab_frame.winfo_children():
                if hasattr(child, 'sql_textbox'):
                    self._refresh_sql_display(child, database)
                    break
    
    def _refresh_sql_display(self, parent, database):
        """刷新SQL显示"""
        if not self.current_requirement or self.current_database != database:
            return
        
        requirement_no = self.current_requirement
        items = self.grouped_data[database][requirement_no]
        show_rollback = parent.rollback_var.get()
        
        # 更新选择标签
        parent.selection_label.configure(
            text=f"📋 {database.upper()} - {requirement_no} ({len(items)}条记录)"
        )
        
        # 生成SQL内容
        sql_content = f"-- {database.upper()}\n"
        sql_content += f"-- {requirement_no}\n\n"
        
        # 按脚本类型分组显示
        ddl_items = [item for item in items if item['script_type'] == 'DDL']
        dml_items = [item for item in items if item['script_type'] == 'DML']
        
        if ddl_items:
            sql_content += "-- ===================\n-- DDL 脚本\n-- ===================\n\n"
            for item in ddl_items:
                sql_content += self._format_sql_item(item, show_rollback)
                sql_content += "\n\n"
        
        if dml_items:
            sql_content += "-- ===================\n-- DML 脚本\n-- ===================\n\n"
            for item in dml_items:
                sql_content += self._format_sql_item(item, show_rollback)
                sql_content += "\n\n"
        
        # 更新文本框
        parent.sql_textbox.configure(state="normal")
        parent.sql_textbox.delete("0.0", "end")
        parent.sql_textbox.insert("0.0", sql_content)
        parent.sql_textbox.configure(state="disabled")
    
    def _format_sql_item(self, item, show_rollback=False):
        """格式化单个SQL项"""
        if show_rollback:
            if item['rollback_script']:
                content = f"-- {item['database']}\n"
                content += f"-- {item['requirement_no']} {item['remark']}\n"
                content += f"-- [RollBack脚本]\n"
                content += item['rollback_script']
            else:
                content = f"-- {item['database']}\n"
                content += f"-- {item['requirement_no']} {item['remark']}\n"
                content += f"-- [无RollBack脚本]"
        else:
            content = f"-- {item['database']}\n"
            content += f"-- {item['requirement_no']} {item['remark']}\n"
            content += item['sql_script']
        
        return content
    
    def _on_parse_error(self, error_message):
        """解析失败处理"""
        self._set_parsing_state(False)
        self.progress_label.configure(text="❌ 解析失败", text_color=("#dc3545", "#e74c3c"))
        messagebox.showerror("❌ 解析失败", f"处理失败:\n{error_message}")
    
    def _update_step_indicator(self, step):
        """更新步骤指示器"""
        self.current_step = step
        for i, (circle, label) in enumerate(self.step_labels, 1):
            if i <= step:
                circle.configure(fg_color="#28a745")
                label.configure(text_color="#ffffff")
            else:
                circle.configure(fg_color="#6c757d")
                label.configure(text_color="#cccccc")
    
    def _clear_all(self):
        """重置所有内容"""
        # 显示初始界面
        if self.db_tabview:
            self.db_tabview.destroy()
            self.db_tabview = None
        
        self.initial_display.pack(fill="both", expand=True, padx=15, pady=(0, 15))
        
        # 重置变量
        self.selected_file_path = ""
        self.file_path_var.set("请选择Excel文件...")
        self.parse_button.configure(state="disabled")
        self.progress_bar.set(0)
        self.progress_label.configure(text="🟢 就绪", text_color=("#28a745", "#20c997"))
        self._update_step_indicator(1)
        
        # 重置统计
        self.stats_text.configure(text="等待解析数据...")
        
        # 清空数据
        self.parsed_data = []
        self.grouped_data = {}
        self.current_database = ""
        self.current_requirement = ""
        self.excel_parser = ExcelParser()
    
    def _show_help(self):
        """显示帮助信息"""
        help_text = """📖 Meiya SQL生成工具使用帮助

📋 新版Excel格式（已更新）:
必须包含6列: 需求号、数据库、脚本类别、SQL脚本、备注、RollBack脚本

✨ 新功能特性:
• 按数据库自动分类（iclaim, cclaim, adapter）
• 按需求号分组显示DDL/DML统计
• SQL脚本格式化展示
• RollBack脚本切换查看

🚀 使用步骤:
1. 选择包含需求号的Excel文件
2. 点击解析，自动按数据库分类
3. 切换数据库选项卡查看分类结果
4. 点击需求号查看格式化的SQL脚本
5. 使用开关切换查看RollBack脚本

💡 SQL格式:
-- 数据库名
-- 需求号 备注信息
SQL语句内容"""
        
        messagebox.showinfo("📖 使用帮助", help_text)
    
    def _on_closing(self):
        """关闭处理"""
        ConfigManager.save_config(self.config)
        self.root.destroy()
    
    def run(self):
        """启动应用"""
        self.root.mainloop()


def main():
    """主函数"""
    try:
        app = MeiyaSQLGenerator()
        app.run()
    except Exception as e:
        print(f"程序启动失败: {e}")
        messagebox.showerror("启动失败", f"程序启动错误:\n{e}")


if __name__ == "__main__":
    main()
